import axios from "axios"
import {API_BASE_URL, HEADER, HEADER_PARAMS} from './proxy.d'
import ngr from 'nprogress'
import {ElMessage} from 'element-plus'
import router from "./router.ts";

const service = axios.create({
    baseURL: API_BASE_URL, timeout: 60000,//过期时间
    withCredentials: true
})
//请求拦截
service.interceptors.request.use(config => {
    //请求头
    if (config.method == 'post' || config.method == 'put') {
        config.headers['Content-Type'] = HEADER_PARAMS
    } else {
        config.headers['Content-Type'] = HEADER
        config.params = config.params || {}
    }
    let Authorization = sessionStorage.getItem('Authorization')
    if (Authorization) {
        config.headers['Authorization'] = Authorization
    }
    //请求进度条
    if (config.url) {
        ngr.start()
    }
    return config
}, error => {
    ngr.done()
    return Promise.reject(`request--------->${error}`)
})
//响应
service.interceptors.response.use((response: any) => {
    ngr.done()
    if (response['headers']['accept-ranges'] == 'bytes') {
        return response
    }
    const res = response.data
    if ([200, 403, 401].indexOf(res.code) !== -1) {
        if (200 == res.code) {
            return res.data
        } else { //未登录
            ElMessage.error('登录状态已失效,请重新登录')
            return Promise.reject(res['msg'])
        }
    } else { //不是成功、未登录、则为后端逻辑异常或自定义返回异常
        ElMessage.error(res['msg'])
        return Promise.reject()
    }
}, (err) => {
    ngr.done()
    const data = err.response.data
    // console.log(err)
    ElMessage.error(data['msg'] || '服务无响应')
    if (data['code'] == 401) {
        router.push('/login').catch(() => true)
    }
    return Promise.reject(err.response.data)
})

export default service
